import { Card, Button, Table, Space, Tag, Modal, message, Tooltip } from 'antd';
import { useState, useEffect } from 'react';
import { Download, Upload, Trash2, RefreshCw, FileText, Plus, AlertTriangle } from 'lucide-react';
import { invoke } from '@tauri-apps/api/tauri';

interface DatabaseFile {
  name: string;
  size: string;
  modified_time: string;
  file_type: string;
  path: string;
}

const DatabasePage = () => {
  const [loading, setLoading] = useState(false);
  const [databaseFiles, setDatabaseFiles] = useState<DatabaseFile[]>([]);
  const [restoreModalVisible, setRestoreModalVisible] = useState(false);
  const [selectedBackup, setSelectedBackup] = useState<DatabaseFile | null>(null);

  const loadDatabaseFiles = async () => {
    setLoading(true);
    try {
      const files = await invoke<DatabaseFile[]>('get_database_files');
      setDatabaseFiles(files);
    } catch (error) {
      message.error(`加载数据库文件失败: ${error}`);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    loadDatabaseFiles();
  }, []);

  const handleCreateBackup = async () => {
    try {
      const backupName = await invoke<string>('create_database_backup');
      message.success(`备份创建成功: ${backupName}`);
      loadDatabaseFiles(); // 重新加载文件列表
    } catch (error) {
      message.error(`创建备份失败: ${error}`);
    }
  };

  const handleRestoreBackup = async (file: DatabaseFile) => {
    setSelectedBackup(file);
    setRestoreModalVisible(true);
  };

  const confirmRestore = async () => {
    if (!selectedBackup) return;
    
    try {
      await invoke('restore_database_backup', { backupPath: selectedBackup.path });
      message.success('数据库恢复成功');
      setRestoreModalVisible(false);
      setSelectedBackup(null);
      loadDatabaseFiles(); // 重新加载文件列表
    } catch (error) {
      message.error(`恢复备份失败: ${error}`);
    }
  };

  const handleDeleteBackup = async (file: DatabaseFile) => {
    Modal.confirm({
      title: '确认删除',
      content: `确定要删除备份文件 "${file.name}" 吗？此操作不可恢复。`,
      okText: '删除',
      okType: 'danger',
      cancelText: '取消',
      onOk: async () => {
        try {
          await invoke('delete_database_backup', { backupPath: file.path });
          message.success('备份删除成功');
          loadDatabaseFiles(); // 重新加载文件列表
        } catch (error) {
          message.error(`删除备份失败: ${error}`);
        }
      },
    });
  };

  const getFileTypeColor = (fileType: string) => {
    switch (fileType) {
      case '当前数据库':
        return 'green';
      case '自动备份':
        return 'blue';
      case '手动备份':
        return 'orange';
      case '共享内存文件':
        return 'purple';
      case '预写日志文件':
        return 'cyan';
      default:
        return 'default';
    }
  };

  const columns = [
    {
      title: '文件名',
      dataIndex: 'name',
      key: 'name',
      render: (text: string, record: DatabaseFile) => (
        <div className="flex items-center">
          <FileText size={16} className="text-accent-500 mr-2" />
          <div>
            <div className="font-medium">{text}</div>
            <div className="text-xs text-gray-500">{record.path}</div>
          </div>
        </div>
      )
    },
    {
      title: '大小',
      dataIndex: 'size',
      key: 'size',
      width: 100,
    },
    {
      title: '修改时间',
      dataIndex: 'modified_time',
      key: 'modified_time',
      width: 150,
    },
    {
      title: '类型',
      dataIndex: 'file_type',
      key: 'file_type',
      width: 120,
      render: (type: string) => (
        <Tag color={getFileTypeColor(type)}>
          {type}
        </Tag>
      )
    },
    {
      title: '操作',
      key: 'action',
      width: 200,
      render: (_: any, record: DatabaseFile) => (
        <Space size="small">
          {record.file_type === '当前数据库' && (
            <Tooltip title="创建备份">
              <Button 
                size="small" 
                type="primary"
                icon={<Plus size={14} />}
                onClick={() => handleCreateBackup()}
              >
                备份
              </Button>
            </Tooltip>
          )}
          {(record.file_type === '自动备份' || record.file_type === '手动备份') && (
            <>
              <Tooltip title="恢复此备份">
                <Button 
                  size="small" 
                  className="btn-secondary"
                  icon={<Upload size={14} />}
                  onClick={() => handleRestoreBackup(record)}
                >
                  恢复
                </Button>
              </Tooltip>
              <Tooltip title="下载备份文件">
                <Button 
                  size="small" 
                  className="btn-secondary"
                  icon={<Download size={14} />}
                  onClick={() => {
                    // 这里可以添加下载功能
                    message.info('下载功能开发中...');
                  }}
                >
                  下载
                </Button>
              </Tooltip>
              <Tooltip title="删除备份">
                <Button 
                  size="small" 
                  danger
                  icon={<Trash2 size={14} />}
                  onClick={() => handleDeleteBackup(record)}
                >
                  删除
                </Button>
              </Tooltip>
            </>
          )}
        </Space>
      ),
    },
  ];

  return (
    <div className="p-6">
      <Card title="数据库管理" className="mb-6">
        <div className="flex justify-between items-center mb-4">
          <div>
            <h2 className="text-xl font-semibold">数据库管理</h2>
            <p className="text-gray-500 text-sm mt-1">
              管理 SCUM 服务器的数据库文件和备份
            </p>
          </div>
          <Space>
            <Button 
              type="primary" 
              icon={<Plus className="w-4 h-4" />}
              onClick={handleCreateBackup}
              disabled={!databaseFiles.some(f => f.file_type === '当前数据库')}
            >
              创建备份
            </Button>
            <Button 
              icon={<RefreshCw className="w-4 h-4" />}
              onClick={loadDatabaseFiles}
              loading={loading}
            >
              刷新
            </Button>
          </Space>
        </div>

        {/* 文件类型说明 */}
        <div className="mb-4 p-3 rounded-lg">
          <div className="flex items-start">
            <AlertTriangle className="w-5 h-5 text-gray-600 dark:text-gray-400 mr-2 mt-0.5" />
            <div className="text-sm text-gray-400 dark:text-gray-300">
              <div className="font-medium mb-1">文件类型说明：</div>
              <div className="grid grid-cols-2 gap-2">
                <div>• <Tag color="green">当前数据库</Tag> - 正在使用的数据库文件</div>
                <div>• <Tag color="blue">自动备份</Tag> - SCUM 服务器自动创建的备份</div>
                <div>• <Tag color="orange">手动备份</Tag> - 用户手动创建的备份</div>
              </div>
            </div>
          </div>
        </div>
        
        <Table 
          columns={columns} 
          dataSource={databaseFiles} 
          loading={loading}
          rowKey="path"
          pagination={{
            pageSize: 10,
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: (total, range) => `第 ${range[0]}-${range[1]} 条/共 ${total} 条`
          }}
        />
      </Card>

      {/* 恢复确认对话框 */}
      <Modal
        title="确认恢复数据库"
        open={restoreModalVisible}
        onOk={confirmRestore}
        onCancel={() => {
          setRestoreModalVisible(false);
          setSelectedBackup(null);
        }}
        okText="确认恢复"
        cancelText="取消"
        okType="danger"
      >
        <div className="py-4">
          <AlertTriangle className="w-8 h-8 text-red-500 mb-3" />
          <p className="text-red-600 font-medium mb-2">警告：此操作将覆盖当前数据库！</p>
          <p className="mb-2">您即将恢复以下备份文件：</p>
          <div className="bg-gray-600 p-3 rounded">
            <p><strong>文件名：</strong>{selectedBackup?.name}</p>
            <p><strong>大小：</strong>{selectedBackup?.size}</p>
            <p><strong>修改时间：</strong>{selectedBackup?.modified_time}</p>
          </div>
          <p className="mt-3 text-sm text-gray-600">
            系统会自动创建当前数据库的安全备份，以防恢复失败。
          </p>
        </div>
      </Modal>
    </div>
  );
};

export default DatabasePage; 